<template>
  <a-modal
    v-model:visible="visible"
    width="800px"
    title-align="start"
    :title="formModel.menuId? '详细': '新增'"
    :top="130"
    :align-center=false
    :mask-closable=false
    :draggable=false
  >
    <a-scrollbar style="max-height:600px; overflow:auto;">
      <a-form
        ref="formModelRef"
        id="addForm"
        label-align="left"
        layout="vertical"
        :label-col-props=labelColProps
        :wrapper-col-props=wrapperColProps
        :model="formModel"
        :rules="rules"
      >
        <a-row justify="space-between">
          <a-col :span="11">
            <a-form-item field="parentId" label="父级菜单">
              <a-tree-select
                v-model="formModel.parentId"
                popup-container="#addForm"
                :field-names="fieldNames"
                :data="menuTreeData"
                :disabled="formDisable"
              >
                <template #tree-slot-icon="{ node }">
                  <icon-folder v-if="node.menuType === 'C'" />
                  <icon-layout v-if="node.menuType === 'M'" />
                </template>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="menuName" label="菜单名称">
              <a-input
                v-model="formModel.menuName"
                placeholder="请输入菜单名称"
                show-word-limit
                allow-clear
                :max-length="10"
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="orderNum" label="显示排序">
              <a-input-number
                v-model="formModel.orderNum"
                mode="button"
                :default-value="0"
                :min="0"
                :max="9999"
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="menuType" label="菜单类型">
              <a-radio-group
                v-model="formModel.menuType"
                type="button"
                @change="menuTypeChange"
              >
                <a-radio value="C">目录</a-radio>
                <a-radio value="M">菜单</a-radio>
                <a-radio value="P">权限</a-radio>
                <a-radio value="L">外链</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'P'" :span="11">
            <a-form-item field="perms" label="权限标识">
              <a-input
                v-model="formModel.perms"
                placeholder="请输入权限标识"
                show-word-limit
                allow-clear
                :max-length="50"
              />
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'C' || formModel.menuType === 'M'" :span="11">
            <a-form-item field="icon" label="菜单图标">
              <icon-select v-model="formModel.icon" />
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'C' || formModel.menuType === 'M'" :span="11">
            <a-form-item field="routeName" label="路由名称">
              <a-input
                v-model="formModel.routeName"
                placeholder="请输入路由名称"
                show-word-limit
                allow-clear
                :max-length="30"
              />
            </a-form-item>
          </a-col>
          <a-col
            v-if="formModel.menuType === 'C' || formModel.menuType === 'M'|| formModel.menuType === 'L'"
            :span="11"
          >
            <a-form-item
              field="routePath"
              :label="formModel.menuType === 'L' ? '外链地址': '路由地址'"
            >
              <a-input
                v-model="formModel.routePath"
                allow-clear
                :max-length="999"
                :placeholder="`请输入${formModel.menuType === 'L' ? '外链地址': '路由地址'}`"
              />
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'C' || formModel.menuType === 'M'" :span="11">
            <a-form-item field="routeComponent" label="组件地址">
              <a-input
                v-model="formModel.routeComponent"
                placeholder="请输入组件地址"
                :disabled="formModel.menuType === 'C'"
              >
                <template #prepend v-if="formModel.menuType === 'M'">
                  /src/views/
                </template>
                <template #append v-if="formModel.menuType === 'M'">
                  .vue
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'C' || formModel.menuType === 'M'" :span="11">
            <a-form-item field="visible" label="菜单状态">
              <a-switch
                v-model="formModel.visible"
                type="round"
                :checked-value="'1'"
                :unchecked-value="'0'"
              >
                <template #checked>显示</template>
                <template #unchecked>隐藏</template>
              </a-switch>
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'C' || formModel.menuType === 'M'" :span="11">
            <a-form-item field="isRefresh" label="是否刷新">
              <a-switch
                v-model="formModel.isRefresh"
                type="round"
                :checked-value="'1'"
                :unchecked-value="'0'"
              >
                <template #checked>刷新</template>
                <template #unchecked>不刷新</template>
              </a-switch>
            </a-form-item>
          </a-col>
          <a-col v-if="formModel.menuType === 'M'" :span="24">
            <a-form-item field="routeProps" label="路由参数">
              <a-textarea
                v-model="formModel.routeProps"
                placeholder="请输入路由参数"
                show-word-limit
                allow-clear
                :max-length="9999"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-scrollbar>
    <template #footer>
      <a-row justify="end">
        <a-button-group>
          <a-button :disabled="loading" @click="cancel">
            取消
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            :disabled="hasUpdatePermission"
            @click="submit"
          >
            确定
          </a-button>
        </a-button-group>
      </a-row>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose, computed } from 'vue';
import { menuTree, addMenu, detailMenu, updateMenu, SysMenu } from '@/api/system/menu';
import { hasPermission } from '@/utils/permission';
import { rules, permission } from '@/views/system/menu/config';
import { Message, ValidatedError } from '@arco-design/web-vue';
import { labelColProps, wrapperColProps } from '@/components/dialog-add/config';
import useLoading from '@/hooks/loading';
import IconSelect from '@/components/icon/icon-select.vue';

const emits = defineEmits(['submit']);

const { loading, setLoading } = useLoading(false);

const fieldNames = ref({
  key: 'menuId',
  title: 'menuName',
  children: 'children'
});

const formModelRef = ref();

const visible = ref<boolean>(false);

const formDisable = ref<boolean>(false);

const formModel = ref<SysMenu>({});

const menuTreeData = ref([]);

const hasUpdatePermission = computed(() => {
  return formModel.value.menuId && !hasPermission([permission.PERMISSION_UPDATE]);
});

const getMenuTree = async () => {
  const { data } = await menuTree();
  convertData(data);
  menuTreeData.value = data;
};

const convertData = (data: any) => {
  data.forEach((item: { icon: any; children: any; }) => {
    delete item.icon;
    if (item.children) {
      convertData(item.children);
    }
  });
};

const menuTypeChange = (value: any) => {
  formModel.value.icon = '';
  formModel.value.routeName = '';
  formModel.value.routePath = '';
  formModel.value.routeComponent = '';
  formModel.value.routeProps = '';
  formModel.value.perms = '';
  if (value === 'C' || value === 'M') {
    formModel.value.visible = '1';
    formModel.value.isRefresh = '0';
    if (value === 'C') {
      formModel.value.routeComponent = 'DEFAULT_LAYOUT';
    }
  }
  if (value === 'P' || value === 'L') {
    formModel.value.visible = '';
    formModel.value.isRefresh = '';
  }
};

const submit = async () => {
  formModelRef.value.validate((errors: undefined | Record<string, ValidatedError>) => {
    if (errors) {
      return;
    }
    setLoading(true);
    if (formModel.value.menuId) {
      updateMenu(formModel.value).then(() => {
        submitSuccess();
      }).finally(() => {
        setLoading(false);
      });
      return;
    }
    addMenu(formModel.value).then(() => {
      submitSuccess();
    }).finally(() => {
      setLoading(false);
    });
  });
};

const submitSuccess = () => {
  cancel();
  emits('submit');
  Message.success('操作成功');
};

const open = async (record: any, disable: boolean) => {
  await getMenuTree();
  if (record && record.menuId) {
    const { data } = await detailMenu(record.menuId);
    formModel.value = data;
  } else {
    formModel.value = { parentId: record?.parentId || '0', menuType: 'C', visible: '1', isRefresh: '0', orderNum: 0 };
  }
  visible.value = true;
  formDisable.value = disable;
  formModelRef.value.clearValidate();
  setLoading(false);
};

const cancel = () => {
  visible.value = false;
};

defineExpose({
  open
});
</script>

<script lang="ts">
export default {
  name: 'MenuDialogAdd'
};
</script>

<style scoped>

</style>